package com.xr.sunnyday.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xr.sunnyday.dao.SetMealDao;
import com.xr.sunnyday.entity.PageResult;
import com.xr.sunnyday.entity.QueryPageBean;
import com.xr.sunnyday.entity.Result;
import com.xr.sunnyday.pojo.Setmeal;
import com.xr.sunnyday.service.SetMealService;
import com.xr.sunnyday.utils.QiNiuUtils;
import freemarker.core.ParseException;
import freemarker.template.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetMealService.class)
public class SetMealServiceImpl implements SetMealService{
    @Autowired
    private SetMealDao setMealDao;

    @Override
    public PageResult findByCondition(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Setmeal> page= setMealDao.findByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    @Transactional
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setMealDao.add(setmeal);
        if(null!=checkgroupIds){
            for (Integer checkgroupId:checkgroupIds) {
                setMealDao.addSetMealCheckGroup(setmeal.getId(),checkgroupId);
            }
        }
        //a.新增套餐后需要重新生成静态页面
        generateMobileStaticHtml();
    }

    @Override
    public Setmeal findBySetMealId(int setMealId) {
        return setMealDao.findBySetMealId(setMealId);
    }

    @Override
    public List<Integer> findSetMealCheckGroup(int setMealId) {
        return setMealDao.findSetMealCheckGroup(setMealId);
    }

    @Override
    public void update(Setmeal setmeal, Integer[] checkgroupIds) {
        //1.先修改套餐内容
        setMealDao.update(setmeal);
        //2.解除关联
        setMealDao.deleteCheckGroupSetMeal(setmeal.getId());
        //3.建立关联
        if(null!=checkgroupIds){
            for (Integer checkgroupId:checkgroupIds){
                setMealDao.addSetMealCheckGroup(setmeal.getId(),checkgroupId);
            }
        }
    }

    @Override
    public void delete(int id) {
        setMealDao.deleteCheckGroupSetMeal(id);
        setMealDao.delete(id);
    }

    @Override
    public List<String> findImgs() {
        return setMealDao.findImgs();
    }

    @Override
    public List<Setmeal> findAll() {
        return setMealDao.findAll();
    }

    @Override
    public Setmeal findDetailById(int id) {
        Setmeal setmeal= setMealDao.findDetailById(id);
        setmeal.setImg(QiNiuUtils.DOMAIN+setmeal.getImg());
        return setmeal;
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setMealDao.findSetmealCount();
    }


    //---------------------------------------------
    @Autowired
    private FreeMarkerConfig freemarkerConfig;

    @Value("${out_put_path}")
    private String out_put_path;

    /**
     * 封装FreeMark方法
     */
    private void generateHtml(String templateFileName, Map<String,Object> dataMap, String outFileName){
        //1.拿到Configuration对象
        Configuration configuration = freemarkerConfig.getConfiguration();

        //缓冲流,加大读写效率
        BufferedWriter writer= null;
        try {
            //2.加载模板文件-已有
            Template template = configuration.getTemplate(templateFileName);
            //3.准备数据->已有
            //4.输出文件路径
            writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFileName),"utf-8"));
            //5.填充数据
            template.process(dataMap, writer);
            //6.刷流
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }finally {
            try {
                //7.关流
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    //b.生成套餐列表、套餐具体详情静态页面
    private void generateMobileStaticHtml(){
        try{
            //1.套餐列表静态页面
            generateSetmealListHtml();
            //2.套餐详情静态页面生成单个就行了，为了测试方便，生成所有的
            generateSetmealDetailHtml();
        }catch(Exception e){
            throw new RuntimeException(e);
        }
    }
        //b.1生成套餐静态页面
    private void generateSetmealListHtml(){
        //1.准备模板文件路径,freemarker配置文件中已经配置好了路径前缀
        String templateName="mobile_setmeal.ftl";
        //2.准备套餐列表页面的数据
        List<Setmeal> setmealList=setMealDao.findAll();
        //2.1.拼图片路径返回
        setmealList.forEach(setmeal->{
            setmeal.setImg(QiNiuUtils.DOMAIN+setmeal.getImg());
        });
        //3.构建数据
        Map<String,Object> dataMap=new HashMap<String,Object>();
        //注意，key值一定要与模板文件中的变量保持一致
        dataMap.put("setmealList",setmealList);
        //4.输出全路径
        String setmealListFile=out_put_path+"mobile_setmeal.html";
        //调用封装的页面生成方法
        generateHtml(templateName,dataMap,setmealListFile);

    }

    //b.2生成套餐详情静态页面
    private void generateSetmealDetailHtml() {
        //1.准备模板文件路径,freemarker配置文件中已经配置好了路径前缀
        String templateName = "mobile_setmeal_detail.ftl";
        // 2.准备数据：把所有套餐都生成详情页面,方便测试
        List<Setmeal> setmealList = setMealDao.findAll();
        // 2.1setmealList中的套餐是没有详情信息，即没有检查组也没有检查项的信息，要查询一遍
        for (Setmeal setmeal : setmealList) {
            // 2.2.获取套餐详情
            Setmeal setmealDetail = setMealDao.findDetailById(setmeal.getId());
            // 2.3设置套餐的图片路径
            setmealDetail.setImg(QiNiuUtils.DOMAIN + setmealDetail.getImg());
            // 3.构建数据
            Map<String,Object>dataMap=new HashMap<String,Object>();
            dataMap.put("setmeal",setmealDetail);
            // 4.输出全路径
            String setmealListFile=out_put_path+"mobile_setmeal_"+setmealDetail.getId()+".html";
            // 调用封装的页面生成方法
            generateHtml(templateName,dataMap,setmealListFile);
        }
    }


    }
